<template>
  <!-- 搜索按钮 -->
  <el-card>
    <!-- 行内表单：搜索框、搜索和重置按钮 -->
    <el-form :inline="true" class="form">
      <el-form-item label="职位搜索">
        <el-input
          placeholder="请输入职位搜索关键字"
          v-model="keyword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          :disabled="keyword ? false : true"
          @click="search"
        >
          搜索
        </el-button>
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 表格：展示角色数组中的数据 -->
  <el-card style="margin: 10px 0">
    <!-- 按钮：增加用户 -->
    <el-button type="primary" size="default" icon="Plus" @click="addRole">
      添加职位
    </el-button>
    <!-- 表格：展示所有角色数组 -->
    <el-table border style="margin: 10px 0" :data="allroleArr">
      <el-table-column type="index" align="center" label="#"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="职位名称"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <!-- row为每一个角色对象 -->
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="setPermisstion(row)"
          >
            分配权限
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateRole(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`确定删除${row.roleName}吗?`"
            width="260px"
            @confirm="removeRole(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout=" prev, pager, next, jumper, ->, sizes, total"
      @current-change="getHasRole"
      @size-change="handler"
    />
  </el-card>
  <!-- 添加职位与更新职位的结构 -->
  <el-dialog
    v-model="dialogVisible"
    :title="roleParams.id ? '更新职位' : '添加职位'"
  >
    <!-- 表单 -->
    <el-form :model="roleParams" :rules="rules" ref="form">
      <el-form-item label="职位名称" prop="roleName">
        <el-input
          placeholder="请输入职位名称"
          v-model="roleParams.roleName"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 插槽：确定和取消按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="default" @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="save">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 抽屉组件:分配用户菜单权限和按钮权限 -->
  <el-drawer v-model="drawer">
    <!-- 插槽：头部 -->
    <template #header>
      <h4>分配菜单和按钮的权限</h4>
    </template>
    <!-- 插槽：树形控件 -->
    <template #default>
      <el-tree
        style="max-width: 600px"
        show-checkbox
        default-expand-all
        :data="menuArr"
        :default-checked-keys="selectArr"
        :props="defaultProps"
        node-key="id"
        ref="tree"
      />
    </template>
    <!-- 插槽：确定和取消按钮 -->
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="handler1">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermission,
  reqRemoveRole,
} from '@/api/acl/role'
import type {
  RoleResponseData,
  RoleData,
  MenuResponseData,
  MunuData,
} from '@/api/acl/role/type'
import useLayoutSettingStore from '@/store/modules/setting'
import { ElMessage } from 'element-plus'

//页码 页面尺寸 搜索关键字
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let keyword = ref<string>('')
//全部角色数组 全部角色数组的长度
let allroleArr = ref<RoleData[]>([])
let total = ref<number>(0)
//layoutSetting仓库
let layoutSetting = useLayoutSettingStore()
//对话框的显示和隐藏
let dialogVisible = ref<boolean>(false)
//收集新增岗位的数据
let roleParams = reactive<RoleData>({
  roleName: '',
})
//获取对话框中的表单实例
let form = ref<any>()
//控制抽屉的显示和隐藏的标识
let drawer = ref<boolean>(false)
//展示树形控件
const defaultProps = {
  children: 'children',
  label: 'name',
}
//用户权限数组
let menuArr = ref<MunuData[]>([])
//存储勾选节点的Id的数组：存储所有叶子节点的Id
let selectArr = ref<number[]>([])
//获取树形控件组件实例
let tree = ref<any>()

//发送请求获取所有角色数组的方法
const getHasRole = async (pager = 1) => {
  //页码
  pageNo.value = pager
  //发送请求获取全部角色数据
  let result: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    allroleArr.value = result.data.records
    total.value = result.data.total
  }
}
//组件挂载完毕：
onMounted(() => {
  //发送请求获取所有角色数组
  getHasRole()
})
//页码大小发生变化时的回调：发送请求获取所有角色（第一页）
const handler = () => {
  //发送请求获取所有角色数组
  getHasRole()
}
//点击搜索按钮的回调
const search = () => {
  //根据关键字，再次发送请求获取所有角色数组
  getHasRole()
  //关键字清空
  keyword.value = ''
}
//点击重置按钮的回调
const reset = () => {
  layoutSetting.refresh = !layoutSetting.refresh
}
//点击添加职位的回调
const addRole = () => {
  //显示对话框
  dialogVisible.value = true
  //清空上一次收集的新增岗位的数据
  Object.assign(roleParams, {
    id: 0,
    roleName: '',
  })
  //清空上一次表单校验的结果
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
//点击编辑职位的回调
const updateRole = (row: RoleData) => {
  //显示对话框
  dialogVisible.value = true
  //数据回显
  Object.assign(roleParams, row)
  //清空上一次表单校验的结果
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
//校验方法
//@ts-ignore
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('职位名称至少两位'))
  }
}
//职位相关的校验规则
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
//点击确认按钮的回调
const save = async () => {
  //只有表单校验通过才能向下执行
  await form.value.validate()
  //发送请求添加职位或更新职位
  let result: any = await reqAddOrUpdateRole(roleParams)
  if (result.code == 200) {
    //隐藏对话框
    dialogVisible.value = false
    //提示文字
    ElMessage({
      type: 'success',
      message: roleParams.id ? '更新成功' : '添加成功',
    })
    //再次发送请求获取全部已有的职位
    getHasRole(roleParams.id ? pageNo.value : 1)
  }
}
//递归函数：获取所有已选中叶子节点的Id
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
//点击分配权限按钮的回调
const setPermisstion = async (row: RoleData) => {
  //显示抽屉
  drawer.value = true
  //回显数据（收集当前要分配权限的职位的数据）
  Object.assign(roleParams, row)
  //发送请求根据职位获取权限的数据
  let result: MenuResponseData = await reqAllMenuList(roleParams.id as number)
  if (result.code == 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
//抽屉确定按钮的回调
const handler1 = async () => {
  //选中节点的Id 半选中节点的Id
  let arr = tree.value.getCheckedKeys()
  let arr1 = tree.value.getHalfCheckedKeys()
  //发送请求给某个Id的角色下发某些Id的权限
  let result: any = await reqSetPermission(roleParams.id as number, [
    ...arr,
    ...arr1,
  ])
  if (result.code == 200) {
    //关闭抽屉
    drawer.value = false
    //消息提示
    ElMessage({
      type: 'success',
      message: '下发权限成功',
    })
    //页面刷新
    window.location.reload()
  }
}
//点击气泡框确定删除按钮的回调
const removeRole = async (rowId: number) => {
  //发送请求删除某个Id的角色
  let result: any = await reqRemoveRole(rowId)
  if (result.code == 200) {
    //消息提示
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //重新发送请求获取所有角色数据
    getHasRole(allroleArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
</script>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
}
</style>
